<?php

namespace app\service;

/**
 * 计数器法限流
 * Class Counter
 */
class Counter {

    private $first_request_time;
    private $request_count = 0; //已请求的次数
    public $limit = 100; //时间窗口内的最大请求数
    public $interval = 60; //时间窗口 s

    public function __construct() {
        $this->first_request_time = time();
    }

    public function grant() {
        $now = time();
        if ($now < $this->first_request_time + $this->interval) {
            //时间窗口内
            if ($this->request_count < $this->limit) {
                $this->request_count++;
                return true;
            }
            return false;
        } else {
            //超出前一个时间窗口后, 重置第一次请求时间和请求总次数
            $this->first_request_time = $now;
            $this->request_count = 1;
            return true;
        }
    }
}